package com.yunshipei.ui.fragment;


import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.RelativeLayout;

import com.yunshipei.EnterApplication;
import com.yunshipei.common.ExitApps;
import com.yunshipei.common.Globals;
import com.yunshipei.common.ProfileResHandler;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.common.net.ProxySettings;
import com.yunshipei.core.common.XCloudException;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.BuildConfig;
import com.yunshipei.enterplorer.R;
import com.yunshipei.inter.ModifyPasCallBack;
import com.yunshipei.manager.UpdateManager;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.H5CustomModel;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.activity.DeveloperActivity;
import com.yunshipei.ui.activity.FontSizeSettingsActivity;
import com.yunshipei.ui.activity.ImageCropActivity;
import com.yunshipei.ui.activity.ModifyPasswordActivity;
import com.yunshipei.ui.activity.MultiActivity;
import com.yunshipei.ui.activity.SSOActivity;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.ui.view.client.H5WebViewClient;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIMClientWrapper;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.model.Conversation;

import static android.app.Activity.RESULT_OK;

public class H5CustomFragment extends H5BaseFragment {

    private static final String BUNDLE_H5_CSUTOM_DATA = "bundle.h5.custom.data";
    private static final int IMAGE_CROP_REQUEST_CODE = 501;

    public static H5CustomFragment newInstance(MainExtraBean mainExtraBean) {
        H5CustomFragment customFragment = new H5CustomFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(BUNDLE_H5_CSUTOM_DATA, mainExtraBean);
        customFragment.setArguments(bundle);

        return customFragment;
    }

    @Bind(R.id.h5_web_view)
    protected WebView mWebView;
    @Bind(R.id.h5_loading_view)
    protected RelativeLayout mLoadingView;

    private MainExtraBean mMainExtraBean;
    private UserInfo mUserInfo;
    private SharedPreferences mPreferences;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMainExtraBean = (MainExtraBean) getArguments().getSerializable(BUNDLE_H5_CSUTOM_DATA);
        if (mMainExtraBean != null) {
            mUserInfo = mMainExtraBean.getUserInfo();
        }
        mPreferences = YspPreferences.getInstance().getSharedPreferences();
    }

    @Override
    public void startProxy() {
        if (!TextUtils.isEmpty(mProxyIP) && 0 != mProxyPort) {
            ProxySettings.setProxy(mWebView, mProxyIP, mProxyPort);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_h5_customer, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mWebView.addJavascriptInterface(redcore, "redcore");
        mWebView.setWebViewClient(new H5WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (mLoadingView.getVisibility() == View.VISIBLE) {
                    mLoadingView.setVisibility(View.INVISIBLE);
                }
            }
        });
        Flowable.just(mMainExtraBean.getH5CustomModel()).flatMap(new Function<H5CustomModel, Publisher<String>>() {
            @Override
            public Publisher<String> apply(H5CustomModel h5CustomModel) throws Exception {
                ProfileResHandler profileResHandler = new ProfileResHandler(mContext, mManagerServer);
                return profileResHandler.mePageFlowable(h5CustomModel.getVersion(), h5CustomModel.getDownloadUrl());
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String url) throws Exception {
                startProxy();
                mWebView.loadUrl(url);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtils.showToast(throwable.getMessage() + ",将使用缓存资源");
                File file = new File(mContext.getFilesDir().getParent() + File.separator + "web_me" + File.separator + "index.html");
                startProxy();
                if (file.exists()) {
                    mWebView.loadUrl("file://" + file.getPath());
                } else {
                    mWebView.loadUrl("file:///android_asset/local/mepage/index.html");
                }
            }
        });
    }

    private Object redcore = new Object() {

        @JavascriptInterface
        public String personalInfo() {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("platform", "android");
                jsonObject.put("appVersion", BuildConfig.VERSION_NAME);
                jsonObject.put("companyTitle", mMainExtraBean.getCompanyTitle());
                jsonObject.put("themeColor", EnterConfig.getInstance().optGlobalColor());
                jsonObject.put("name", mUserInfo.getName());
                jsonObject.put("position", mUserInfo.getPosition());
                jsonObject.put("isForTest", BuildConfig.DEBUG ? 1 : 0);
                jsonObject.put("avatar", mUserInfo.getAvatar());
                jsonObject.put("autoUpdate", mPreferences.getBoolean(Globals.SP_SPLASH_CHECK_UPDATE, true));
                jsonObject.put("developer", mPreferences.getBoolean(Globals.YSP_DEBUG, false));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return jsonObject.toString();
        }

        @JavascriptInterface
        public void userAvatarTapped() {
            startActivityForResult(new Intent(getContext(), ImageCropActivity.class), IMAGE_CROP_REQUEST_CODE);
        }

        @JavascriptInterface
        public void settingOperation(String ops) {
            if (!TextUtils.isEmpty(ops)) {
                if ("ssos".equals(ops)) {
                    startActivity(new SSOActivity.SSOActivityIntentBuilder(getActivity()).setMainData(mMainExtraBean).getIntent());
                } else if ("font".equals(ops)) {
                    startActivity(new FontSizeSettingsActivity.FontSizeSettingsIntentBuilder(getActivity()).getIntent());
                } else if ("clearCache".equals(ops)) {
                    DialogHelper.getAlertDialogCancelable(getActivity(), "将清空Enterplorer本地缓存数据？", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            final WaitDialog waitDialog = new WaitDialog(getActivity());
                            waitDialog.setMessage("正在删除缓存...");
                            Flowable.create(new FlowableOnSubscribe<Boolean>() {
                                @Override
                                public void subscribe(FlowableEmitter<Boolean> e) throws Exception {
                                    String path = Environment.getExternalStorageDirectory() + "/yunshipei";
                                    String cachePath = getActivity().getCacheDir().getPath();
                                    BaseUtil.deletePathReal(path);
                                    BaseUtil.deletePathReal(cachePath);
                                    e.onNext(true);
                                }
                            }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) throws Exception {
                                            waitDialog.dismiss();
                                            ToastUtils.showToast("清空缓存成功");
                                        }
                                    });
                        }
                    }).show();
                } else if ("clearChats".equals(ops)) {
                    DialogHelper.getAlertDialogCancelable(getActivity(), "将清空所有个人和群的聊天记录？", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null || RongIM.getInstance().getRongIMClient().getConversationList() == null) {
                                ToastUtils.showToast("没有聊天会话记录");
                                return;
                            }
                            List<Conversation> conversations = RongIM.getInstance().getRongIMClient().getConversationList();
                            RongIMClientWrapper wrapper = RongIM.getInstance().getRongIMClient();
                            for (Conversation conversation : conversations) {
                                wrapper.clearMessages(conversation.getConversationType(), conversation.getTargetId());
                            }
                            EventBus.getDefault().post(new YspEvent.MessageCountClearEvent());
                            ToastUtils.showToast("已清空所有聊天记录");
                        }
                    }).show();
                } else if ("changePsw".equals(ops)) {
                    DialogHelper.checkPasswordDialog(getActivity(), new ModifyPasCallBack() {
                        @Override
                        public void oldPasCheckFinished() {
                            //验证成功，进入密码修改界面
                            startActivity(new ModifyPasswordActivity.ModifyPwdActivityIntentBuilder(mContext).setMainData(mMainExtraBean).getIntent());
                        }
                    });
                }
            }
        }

        @JavascriptInterface
        public void openSettings() {
            startActivity(new MultiActivity.MultiActivityIntentBuilder(getActivity()).setMainData(mMainExtraBean).setTargetPartClazzName(SettingsFragment.class.getName()).getIntent());
        }

        @JavascriptInterface
        public void safeExit() {
            new ExitApps(getActivity()).showConfirm();
        }

        @JavascriptInterface
        public void autoUpdate(boolean open) {
            mPreferences.edit().putBoolean(Globals.SP_SPLASH_CHECK_UPDATE, open).apply();
        }

        @JavascriptInterface
        public void openDeveloper() {
            startActivity(new DeveloperActivity.DeveloperIntentBuilder(getActivity()).setUserInfo(mUserInfo).getIntent());
        }

        @JavascriptInterface
        public void changeDeveloper(boolean status) {
            mPreferences.edit().putBoolean(Globals.YSP_DEBUG, status).apply();
        }

        @JavascriptInterface
        public void checkVersion() {
            UpdateManager updateManager = new UpdateManager(getActivity(), true);
            updateManager.checkUpdate(mUserInfo.getCompanyId());
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode && data != null && requestCode == IMAGE_CROP_REQUEST_CODE) {
            String path = data.getStringExtra(ImageCropActivity.RESULT_FILE_PATH);
            if (!TextUtils.isEmpty(path) && new File(path).exists()) {
                uploadPersonalAvator(path);
            }
        }
    }

    private void uploadPersonalAvator(final String path) {
        Flowable.just(path).flatMap(new Function<String, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(String s) throws Exception {
                return HttpMethods.getInstance().modifyPersonalAvatar(new File(path), mUserInfo.getUuid());
            }
        }).flatMap(new Function<JSONObject, Publisher<String>>() {
            @Override
            public Publisher<String> apply(JSONObject jsonObject) throws Exception {
                int status = jsonObject.optInt("status", 0);
                String errorMsg;
                if (status == 1) {
                    String imageUrl = jsonObject.optString("data");
                    if (!TextUtils.isEmpty(imageUrl)) {
                        return Flowable.just(imageUrl);
                    }
                    errorMsg = "接口异常，请联系管理员";
                } else {
                    errorMsg = jsonObject.optString("message", "未知接口异常，请联系管理员");
                }
                return Flowable.error(new XCloudException(errorMsg));
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String url) throws Exception {
                mWebView.loadUrl("javascript: updateAvatar('" + url + "');");
                mPreferences.edit().putString("avatar", Uri.fromFile(new File(path)).toString()).apply();
                io.rong.imlib.model.UserInfo newUserInfo = new io.rong.imlib.model.UserInfo(mUserInfo.getUuid(), mUserInfo.getName(), Uri.parse(url));
                if (RongContext.getInstance() != null) {
                    RongUserInfoManager.getInstance().setUserInfo(newUserInfo);
                    RongContext.init(EnterApplication.getApp());
                }
                RongIM.getInstance().refreshUserInfoCache(newUserInfo);
                RongIM.getInstance().setCurrentUserInfo(newUserInfo);
                EventBus.getDefault().post(new YspEvent.UserAvatarChangedEvent(mUserInfo.getUuid(), url));
                mUserInfo.setAvatar(url);
                DatabaseUtil dataToastUtils = new DatabaseUtil();
                dataToastUtils.updateUserInfoById(mPreferences.getString("uuid", ""), url);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtils.showToast(throwable.getMessage());
            }
        });
    }

    @Override
    public void onDestroyView() {
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroyView();

    }

    @Override
    public boolean pageCanGoBack() {
        return mWebView != null && mWebView.canGoBack();
    }

    @Override
    public void pageGoBack() {
        if (mWebView != null) {
            mWebView.goBack();
        }
    }
}
